package com.msh.automatic.android.control.script.task

import android.util.Log
import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONObject
import com.msh.automatic.android.control.script.service.ScriptAccessibilityService
import com.msh.automatic.android.control.script.util.AccessibilityServiceUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.reflect.full.createInstance
import kotlin.reflect.full.primaryConstructor
import kotlin.system.exitProcess

object TaskManager {

    // 正在处理的
    val TAG = "TASK"
    // 等待中的任务
    var waitTasks = Channel<Task>(Channel.UNLIMITED)
    var token = ""

    private var job: Job? = null
    private var jobActive: Boolean = true

    fun start(){
        job=GlobalScope.launch {
            while (jobActive) {
                val task = waitTasks.receive()
                try {
                    Log.d(TAG, "开始执行任务: ${System.currentTimeMillis()} ${task.getTaskLogId()} ${task.taskLog.toJSONString()}")
                    this@TaskManager.token = task.token
                    task.run(ScriptAccessibilityService.scriptAccessibilityService)
                }catch (e:Exception){
                    Log.e(TAG, "执行任务异常: ${System.currentTimeMillis()} ${task.getTaskLogId()} ${task.taskLog.toJSONString()}",e)
                }
                AccessibilityServiceUtil.goHome(ScriptAccessibilityService.scriptAccessibilityService)
                delay(3_000)  // 30秒
            }
        }
    }
    fun startTask(task: JSONObject,taskLog: JSONObject,token:String){
        val kClass = Class.forName("com.msh.automatic.android.control.script.task."+task.getString("id")).kotlin
        val constructor = kClass.primaryConstructor!!
        val taskInstance = constructor.call(task,taskLog,token) as Task
        this.waitTasks.trySend(taskInstance)
    }
}